package rbac

import (
	"context"
	"gitee.com/bobo-rs/creative-framework/pkg/utils"
	"gitee.com/bobo-rs/innovideo-services/framework/dao"
	"gitee.com/bobo-rs/innovideo-services/framework/model"
	"gitee.com/bobo-rs/innovideo-services/framework/model/entity"
	"gitee.com/bobo-rs/innovideo-services/library/exception"
	"github.com/gogf/gf/v2/frame/g"
)

// SaveDepartmentRoles 保存部门绑定角色数据
func (r *sRbac) SaveDepartmentRoles(ctx context.Context, departId uint, roleId ...uint) error {
	if len(roleId) == 0 {
		return exception.New(`缺少角色ID`)
	}
	// 迭代处理部门权限角色绑定
	adds := make([]entity.DepartmentRoles, 0)
	for _, rid := range roleId {
		adds = append(adds, entity.DepartmentRoles{
			DepartId: departId,
			RoleId:   rid,
		})
	}

	// 移除之前绑定
	_, _ = dao.DepartmentRoles.Ctx(ctx).
		Where(dao.DepartmentRoles.Columns().DepartId, departId).
		Delete()

	// 绑定数据
	_, err := dao.DepartmentRoles.Ctx(ctx).
		OmitEmpty().
		Insert(adds)
	if err != nil {
		return exception.New(`部门绑定角色失败，请重试`)
	}
	return nil
}

// GetDepartRoleIdByDepartId 通过部门ID获取关联的角色ID
func (r *sRbac) GetDepartRoleIdByDepartId(ctx context.Context, departId ...uint) ([]uint, error) {
	var roleIdArr []model.DepartmentRoleId
	err := dao.DepartmentRoles.Ctx(ctx).
		Where(dao.DepartmentRoles.Columns().DepartId, departId).
		Scan(&roleIdArr)
	if err != nil {
		return nil, exception.New(`暂无数据`)
	}

	// 处理角色ID
	return utils.NewArray(roleIdArr).Units(dao.DepartmentRoles.Columns().RoleId), nil
}

// GetPermissionsIdByDepartId 通过部门ID获取权限ID集合
func (r *sRbac) GetPermissionsIdByDepartId(ctx context.Context, departId ...uint) ([]uint, error) {
	// 获取角色ID
	roleId, err := r.GetDepartRoleIdByDepartId(ctx, departId...)
	if err != nil {
		return nil, err
	}
	// 获取权限ID集合
	return r.GetPermissionsIdByRoleId(ctx, roleId...)
}

// RemoveDepartmentRolesByRoleId 通过角色ID删除部门绑定
func (r *sRbac) RemoveDepartmentRolesByRoleId(ctx context.Context, roleId uint) error {
	b, _ := r.DepartmentRoleModel().Exists(ctx, g.Map{
		dao.DepartmentRoles.Columns().RoleId: roleId,
	})
	// 角色未关联到部门
	if b == false {
		return nil
	}

	// 删除角色关联部门
	_, err := dao.DepartmentRoles.Ctx(ctx).
		Where(dao.DepartmentRoles.Columns().RoleId, roleId).
		Delete()
	if err != nil {
		return exception.New(`解除角色关联部门失败`)
	}
	return nil
}

// RemoveDepartmentRoleByDepartId 通过部门ID解除角色关联
func (r *sRbac) RemoveDepartmentRoleByDepartId(ctx context.Context, departId uint) error {
	b, _ := r.DepartmentRoleModel().Exists(ctx, g.Map{
		dao.DepartmentRoles.Columns().DepartId: departId,
	})
	// 未关联角色
	if b == false {
		return nil
	}

	// 删除关联
	_, err := dao.DepartmentRoles.Ctx(ctx).
		Where(dao.DepartmentRoles.Columns().DepartId, departId).
		Delete()
	if err != nil {
		return exception.New(`解除角色关联失败`)
	}
	return nil
}
